package com.evildog.workspace.system.application.service.impl;

import com.evildog.workspace.dependencies.mybatis.base.TableLinkService;
import com.evildog.workspace.security.jwt.util.SecurityUtil;
import com.evildog.workspace.system.application.bo.UiPermissionBO;
import com.evildog.workspace.system.application.entity.ComponentPermission;
import com.evildog.workspace.system.application.entity.MenuPermission;
import com.evildog.workspace.system.application.mapper.ComponentPermissionMapper;
import com.evildog.workspace.system.application.mapper.MenuPermissionMapper;
import com.evildog.workspace.system.application.mapper.RoleComponentPermissionLinkMapper;
import com.evildog.workspace.system.application.mapper.RoleMenuPermissionLinkMapper;
import com.evildog.workspace.system.application.service.RoleService;
import com.evildog.workspace.system.application.service.UiPermissionService;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Multimaps;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@AllArgsConstructor
public class UiPermissionServiceImpl implements UiPermissionService {

    private final MenuPermissionMapper menuPermissionMapper;
    private final ComponentPermissionMapper componentPermissionMapper;

    private final RoleService roleService;

    private final RoleMenuPermissionLinkMapper roleMenuPermissionLinkMapper;
    private final RoleComponentPermissionLinkMapper roleComponentPermissionLinkMapper;

    private final TableLinkService tableLinkService;

    @Override
    public List<UiPermissionBO> getAllUiPermissions() {
        Long userId = SecurityUtil.getUserId();

        // 查询出用户在平台中的所有菜单和组件权限
        List<MenuPermission> menuPermissions = roleService.getMenuPermissions(userId);
        List<ComponentPermission> componentPermissions = roleService.getComponentPermissions(userId);

        // key menuId value List<ComponentPermission>
        ImmutableListMultimap<Long, ComponentPermission> mapComponentPermissions = Multimaps.index(componentPermissions, ComponentPermission::getMenuPermissionId);

        List<UiPermissionBO> userPermissions = new ArrayList<>();

        menuPermissions.forEach(menuPermission -> userPermissions.add(
                new UiPermissionBO().setMenu(menuPermission.getCode())
                        .setActions(
                                mapComponentPermissions.get(menuPermission.getId())
                                        .stream().map(ComponentPermission::getCode)
                                        .collect(Collectors.toList())
                        )
        ));

        return userPermissions;
    }
}
